package com.jhhc.Http.Service;

import com.jhhc.Http.Pojo.RequestPojo;
import com.jhhc.Http.Pojo.TokenPojo;
import com.jhhc.utils.DateConvertUtil;
import dm.jdbc.filter.stat.json.JSONObject;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;

@Service
public class GetUrlService  {

    //获取token
    public static JSONObject getRhdbToken(){
        TokenPojo tokenPojo = new TokenPojo();

        String appkey = "cc2e0d61194d4587880d214c12cd872a";
        String appsecret = "a43d6ecc05114d63";
        String nonce = RandomStringUtils.randomAlphanumeric(8);
        Long timestamp = DateConvertUtil.getTimeStamp(0);
        String sige=   DigestUtils.sha1Hex("appkey="+appkey +"&appsecret="+appsecret+"&nonce="+nonce+"&timestamp="+timestamp);
        tokenPojo.setSign(sige);
        tokenPojo.setAppkey(appkey);
        tokenPojo.setNonce(nonce);
        tokenPojo.setTimestamp(timestamp);
        return new JSONObject(tokenPojo);
    }



    //封装方法  根据不同链接获取不同token
    public static JSONObject getTokenUrl(String url) throws Exception {
        CloseableHttpClient httpClient = HttpClients.createDefault();  //http请求
        HttpPost tokenHttpPost = new HttpPost(url);
        //调用获取token方法，根据返回加密字符串获取token
        tokenHttpPost.setEntity(new StringEntity(String.valueOf(getRhdbToken()), ContentType.APPLICATION_JSON));

        CloseableHttpResponse tokenResponse = httpClient.execute(tokenHttpPost);

        System.out.println(tokenResponse.getStatusLine().getStatusCode() + "\n");
        HttpEntity tokenEntity = tokenResponse.getEntity();
        String tokenResponseContent = EntityUtils.toString(tokenEntity, "UTF-8"); //返回json




        JSONObject  json = new JSONObject(tokenResponseContent); //string转json
        String message = String.valueOf(json.getMap().get("message"));



        return  new JSONObject(message);

    }




}
